package org.telegram.bot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.delay.IDelayEvent;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.StatusEnum;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.telegram.bot.domain.BotGroup;
import org.telegram.bot.domain.BotInfo;
import org.telegram.bot.domain.BotMessage;
import org.telegram.bot.domain.BotStartApp;
import org.telegram.bot.emums.BotCommonEnums;
import org.telegram.bot.emums.RedisCacheKeyEnums;
import org.telegram.bot.handle.IBotSendMessage;
import org.telegram.bot.service.IJoinGroupService;
import org.telegram.telegrambots.meta.api.methods.groupadministration.RestrictChatMember;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.ChatPermissions;
import org.telegram.telegrambots.meta.api.objects.MessageEntity;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.api.objects.message.Message;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardRow;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wyx
 * @Date: 2023/5/27 23:01
 */
@Service
public class JoinGroupServiceImpl implements IJoinGroupService, IBotSendMessage {

    @Resource
    private IDelayEvent<BotMessage> delayEvent;
    
    @Resource
    private  RedisCache redisCache;
    @Override
    public void handle(Update update, Long chatId, String botId) {
        BotGroup chatGroup = getGroupInfo(chatId);
        //群验证是关闭的
        if(StatusEnum.DISABLE.getCode().equals(chatGroup.getChatVerify().getStatus())){
            return;
        }
        BotInfo botInfo = getBotInfo(botId);
        //删除加群信息
        sendAsync(botId, DeleteMessage.builder().chatId(chatId).messageId(update.getMessage().getMessageId()).build());
        //艾特人实体
        for (User newChatMember : update.getMessage().getNewChatMembers()) {

            if(chatGroup.getChatVerify().getBanTime()>=0) {
                Long timeL = DateUtil.currentSeconds() + chatGroup.getChatVerify().getBanTime();
                //限制聊天
                sendAsync(botId, RestrictChatMember.builder()
                        .chatId(chatId)
                        .userId(newChatMember.getId())
                        .untilDate(timeL.intValue())
                        .permissions(ChatPermissions.builder().canSendMessages(false).build())
                        .build());
            }
            
            //编辑消息
            SendMessage message = SendMessage.builder().chatId(chatId).text("").build();
            //添加站位符号
            Map<String,Object> map = new HashMap<>();
            map.put("timeOut",chatGroup.getChatVerify().getTimeOut());
            //格式化消息
            message.setText("@"+newChatMember.getId()+"\n"+StrUtil.format(chatGroup.getChatVerify().getContent(),map));
            
            List<InlineKeyboardRow> keyboard = new ArrayList<>();

            InlineKeyboardRow buttons = new InlineKeyboardRow();
            InlineKeyboardButton btn = new InlineKeyboardButton("开始验证");
            btn.setUrl(BotCommonEnums.getWebApp(botInfo.getBotName(),botInfo.getBotApp(),new BotStartApp().setRouter(BotCommonEnums.ROUTER_VERIFY).setBotId(Long.valueOf(botId)).setChatId(chatId).setUserId(newChatMember.getId()),false).toString());
            buttons.add(btn);
            keyboard.add(buttons);

            message.setReplyMarkup(InlineKeyboardMarkup.builder().keyboard(keyboard).build());
            
            //@人
            message.setEntities(Collections.singletonList(MessageEntity.builder()
                    .user(newChatMember)
                    .type("text_mention")
                    .offset(0)
                    .length(newChatMember.getId().toString().length() + 1)
                    .build()));
            
            Message msg = send(botId,message);
            BotMessage botMessage = new BotMessage();
            botMessage.setId(newChatMember.getId());
            botMessage.setBotId(botId);
            botMessage.setMessageId(msg.getMessageId());
            botMessage.setTimeout(chatGroup.getChatVerify().getTimeOut());
            botMessage.setCreateTime(new Date());
            botMessage.setUser(newChatMember);
            botMessage.setChatId(chatId);
            //添加到删除消息，防止用户不验证，就无法删除用户消息
            delayEvent.addToDelayQueue(botMessage);
            
            //存入redis,提供网页验证
            redisCache.setCacheObject(RedisCacheKeyEnums.BOT_VALIDATE.getKey(botId,chatId+":"+newChatMember.getId()),botMessage,chatGroup.getChatVerify().getTimeOut().intValue(), TimeUnit.SECONDS);
        }
    }

}
